package com.learning.security.service;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.learning.security.controller.vo.RoleSaveReqVO;
import com.learning.security.dal.dataobject.AdminRoleDO;
import com.learning.security.dal.dataobject.AdminUserRoleDO;
import com.learning.security.dal.mysql.AdminRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdminRoleServiceImpl implements AdminRoleService {
    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private AdminUserRoleService adminUserRoleService;

    @Override
    public boolean createRole(RoleSaveReqVO reqVO) {

        return Db.save(new AdminRoleDO().setName(reqVO.getName())
                .setCode(reqVO.getCode())
                .setSort(reqVO.getSort())
                .setRemark(reqVO.getRemark())
                .setStatus(reqVO.getStatus())
                .setType(1));
    }

    @Override
    public Collection<? extends GrantedAuthority> buildGrantedAuthority(Long userId) {
        List<AdminUserRoleDO> userRoleList = adminUserRoleService.listByUserId(userId);
        return userRoleList.stream().map(userRole -> adminRoleMapper.selectById(userRole.getRoleId()))
                .map(AdminRoleDO::getCode)
                .map(roleCode -> new SimpleGrantedAuthority(roleCode))
                .collect(Collectors.toList());
    }

    @Override
    public AdminRoleDO getRoleByRoleId(Long roleId) {
        return adminRoleMapper.selectById(roleId);
    }
}
